<style>
    body {
        padding: 15px 10px
    }

    body .layui-form fieldset.layui-elem-field {
        margin: 0 0 10px 0
    }

    body .i18n-tran {
        cursor: pointer
    }
</style>
<script>
    // 表单
    layui.use(['element', 'form', 'upload', 'layedit', 'laydate', 'colorpicker', 'layer', 'util'], function () {
        var form = layui.form,
            upload = layui.upload,
            layedit = layui.layedit,
            laydate = layui.laydate,
            colorpicker = layui.colorpicker,
            layer = layui.layer,
            util = layui.util,
            $ = layui.jquery;

        var site_url = '{$site_url}';
        var lang = '{$lang}';
        var translate_api, suggest_api;
        translate_api = 'https://translate.googleapis.com/translate_a/single';
        // translate_api = site_url + '/api/google_translate';
        suggest_api = 'https://www.google.com/complete/search';
        // suggest_api = 'https://suggestqueries.google.com/complete/search';
        suggest_api = site_url + '/api/fetch?method=get&url=' + suggest_api;


        // 获取应用、控制器和方法
        var module = '{$module}'.toLowerCase(),
            controller = '{$controller}'.toLowerCase(),
            action = '{$action}'.toLowerCase();

        // 如果非框架内
        if (self.frameElement && self.frameElement.tagName == 'IFRAME' && action !== 'index') {
            if (parent.layer.getFrameIndex(window.name))
                $('form.layui-form .layui-elem-field').remove();
            else
                !$('form.layui-form .layui-elem-field').length && $('form.layui-form').prepend('<fieldset class="layui-elem-field layui-field-title"><legend>' + (action == 'create' ? '{$localize.add}' : (action == 'edit' ? '{$localize.edit}' : '{$localize.info}')) + '</legend></fieldset>');
        }

        // 日期
        $('form .date').each(function () {
            laydate.render({
                elem: $(this).attr('id') ? '#' + $(this).attr('id') : 'input[name="' + $(this).attr('name') + '"]',
                type: $(this).data('type') || 'date'
            });
        });

        // 颜色
        $('form .color').each(function () {
            var input_id = $(this).attr('id') || $(this).attr('name');
            $(this).parent().parent().append('<div class="layui-inline" style="left: -11px;"><div id="' + input_id + '-render"></div></div>');
            colorpicker.render({
                elem: '#' + input_id + '-render',
                done: function (color) {
                    $('input[name="' + input_id + '"]').val(color);
                }
            });
        });

        // 上传
        $('form .upload').each(function () {
            var input_id = $(this).attr('id') || $(this).attr('name');
            $(this).parent().append('<div class="layui-upload-list" style="position:relative;"></div>');
            $(this).parent().parent().append('<button type="button" class="layui-btn layui-btn-primary" id="' + input_id + '-render"><i class="layui-icon layui-icon-upload"></i> {$localize.upload}</button>');
            if (/\.(gif|jpg|jpeg|png|bmp|webp|psd|svg|tiff)$/gi.test($(this).val())) {
                $(this).parent().find('.layui-upload-list').html('<i class="layui-icon layui-icon-close-fill" style="position:absolute;bottom:-10px;left:-10px;opacity:0.8;cursor:pointer;"></i><img src="' + $(this).val() + '" alt="Preview" style="max-width:92px" onerror="this.parentNode.innerHTML=\'404 Error\'" />');
            }
            upload.render({
                elem: '#' + input_id + '-render',
                url: site_url + '/' + lang + '/' + module + '/media/upload.html',
                data: {},
                before: function () {
                    layer.load();
                },
                done: function (res, index, upload) {
                    layer.closeAll('loading');
                    if (res.code > 0) return layer.msg(res.msg, { icon: 2 });
                    //上传成功
                    $(this.item).prev().find('input[name="' + input_id + '"], input[id="' + input_id + '"]').val(res.data.src)
                    if (/\.(gif|jpg|jpeg|png|bmp|webp|psd|svg|tiff)$/gi.test(res.data.src)) {
                        $(this.item).prev().find('.layui-upload-list').html('<i class="layui-icon layui-icon-close-fill" style="position:absolute;bottom:-10px;left:-10px;opacity:0.8;cursor:pointer;"></i><img src="' + res.data.src + '" alt="Preview" style="max-width:92px" onerror="this.parentNode.innerHTML=\'404 Error\'" />');
                    }
                },
                error: function (index, upload) {
                    layer.closeAll('loading');
                }
            });
        });
        $('form .upload').change(function () {
            if (/\.(gif|jpg|jpeg|png|bmp|webp|psd|svg|tiff)$/gi.test($(this).val())) {
                $(this).parent().find('.layui-upload-list').html('<i class="layui-icon layui-icon-close-fill" style="position:absolute;bottom:-10px;left:-10px;opacity:0.8;cursor:pointer;"></i><img src="' + $(this).val() + '" alt="Preview" style="max-width:92px" onerror="this.parentNode.innerHTML=\'404 Error\'" />');
            } else {
                $(this).parent().find('.layui-upload-list').html(null);
            }
        });
        $('form .layui-upload-list').on('click', '.layui-icon-close-fill', function () {
            $(this).parent().prev().val(null);
            $(this).parent().html(null);
        });

        // layedit富文本
        var editors = [];
        layedit.set({
            uploadImage: {
                url: site_url + '/' + lang + '/' + module + '/media/upload.html', //接口url
                type: 'post', //默认post
            }
        });
        $('form .editor').each(function () {
            var editor_id = $(this).attr('id') || $(this).attr('name');
            $(this).attr('id', editor_id);
            $(this).attr('lay-verify', editor_id);
            editors[editor_id] = layedit.build(editor_id, {
                tool: [
                    'strong', //加粗
                    'italic', //斜体
                    'underline', //下划线
                    'del', //删除线
                    '|', //分割线
                    'left', //左对齐
                    'center', //居中对齐
                    'right', //右对齐
                    '|', //分割线
                    'link', //超链接
                    'unlink', //清除链接
                    'face', //表情
                    'image', //插入图片
                ]
            });
        });

        // 监听提交
        form.on('submit(submit)', function (data) {
            // 验证国际化字段错误
            if ($(data.elem).hasClass('check-i18n')) {
                var err = chk_err();
                if (err.length) {
                    $(data.form).find('#chk-res').html('<pre>' + err.join('\n') + '</pre>');
                    $(data.form).find('chk-loading').addClass('layui-hide');
                    return layer.alert(err.shift(), { icon: 2 });
                }
            }

            if ('undefined' !== typeof KindEditor && window.editor1) {
                data.field.content = window.editor1.html();
            }
            for (var editor in editors) {
                data.field[editor] = layedit.getContent(editors[editor]);
            }
            $.post(site_url + '/' + lang + '/' + module + '/' + controller + '/' + (action == 'edit' ? 'update' : 'save' + (action == 'create' ? '' : '_' + action)) + '.html', data.field, function (res) {
                if (res.code) return layer.alert(res.msg, { title: '{$localize.info}', icon: 2, btn: ['{$localize.ok}'] });
                layer.alert(res.msg, { title: '{$localize.info}', icon: 1, btn: ['{$localize.ok}'] });
                setTimeout(function () {
                    var _ta = window, parentIndex = parent.layer.getFrameIndex(window.name);
                    if (typeof parentIndex !== 'undefined') {
                        parent.layer.close(parentIndex);
                        _ta = parent.window;
                    }
                    if (typeof _ta.layui.table !== 'undefined' && _ta.layui.table.index == 1 && _ta.render && _ta.render.elem) {
                        _ta.layui.table.reload(_ta.render.elem.replace(/#/, ''));
                    } else if (typeof res.url !== 'undefined' && res.url) {
                        _ta.location.href = res.url;
                    } else {
                        _ta.location.reload();
                    }
                }, 1000);
            }, 'json');
            return false;
        });

        // 语言国际化
        var i18nTimer = null;
        $('form.i18n textarea[name="q"], form.i18n textarea[name="to"]').on('blur input', function (e) {
            if (i18nTimer) return false;
            i18nTimer = setTimeout(function () {
                var str = $.trim($(e.target).val());
                var n = str.split("\n").length;
                var s = '';
                for (var i = 1; i <= n; i++) {
                    s += i + "\n";
                }
                $(e.target).parent().prev().find('textarea[disabled="disabled"]').val(s);
                $(e.target).parent().parent().next().find('.layui-word-aux').text('{$localize.lines}' + ' ' + n);
                clearTimeout(i18nTimer);
                i18nTimer = null;
            }, 100);
        });
        $('form.i18n textarea[name="q"], form.i18n textarea[name="to"]').resize(function (e) {
            if (i18nTimer) return false;
            i18nTimer = setTimeout(function () {
                $(e.target).parent().prev().find('textarea[disabled="disabled"]').height($(e.target).height());
                clearTimeout(i18nTimer);
                i18nTimer = null;
            }, 100);
        });
        $('form.i18n textarea[name="q"], form.i18n textarea[name="to"]').scroll(function (e) {
            $(this).parent().prev().find('textarea[disabled="disabled"]').scrollTop($(this).scrollTop());
        });

        // 语言框改变
        $('form select[lay-filter="i18nsltl"]').length && fetch_str();
        form.on('select(i18nsltl)', function (data) {
            var st = $(data.elem).attr('name');
            var voice = $(data.elem).children('option:selected').data('voice');
            if (voice) {
                $('form.i18n .speak-' + st + '-voice').children('button').removeClass('layui-btn-disabled').attr('disabled', false);
            } else {
                $('form.i18n .speak-' + st + '-voice').children('button').addClass('layui-btn-disabled').attr('disabled', true);
            }
            fetch_str()
        });
        function fetch_str() {
            var loading = layer.load(2);
            $.post(site_url + '/' + lang + '/' + module + '/' + controller + '/fetch.html', {
                tl: $('form.i18n select[name="tl"] option:selected').val()
            }, function (res) {
                layer.close(loading);
                if (res.code) return layer.alert(res.msg, { title: '{$localize.info}', icon: 2, btn: ['{$localize.ok}'] }, function (index) {
                    layer.close(index);
                });
                var n = res.data.split("\n").length;
                var m = res.todata.split("\n").length;
                var ni = '';
                for (var i = 1; i <= n; i++) {
                    ni += i + "\n";
                }
                var mi = '';
                for (var i = 1; i <= m; i++) {
                    mi += i + "\n";
                }
                $('form.i18n textarea[name="q"]').val(res.data);
                $('form.i18n textarea[name="q"]').parent().prev().find('textarea[disabled="disabled"]').val(ni);
                $('form.i18n textarea[name="q"]').parent().parent().next().find('.layui-word-aux').text('{$localize.lines}' + ' ' + n);
                $('form.i18n textarea[name="to"]').val(res.todata);
                $('form.i18n textarea[name="to"]').parent().prev().find('textarea[disabled="disabled"]').val(mi);
                $('form.i18n textarea[name="to"]').parent().parent().next().find('.layui-word-aux').text('{$localize.lines}' + ' ' + m);
            }, 'json');
        }

        // 生成语言包
        form.on('submit(generate)', function (data) {
            $.post(site_url + '/' + lang + '/' + module + '/' + controller + '/generate.html', data.field, function (res) {
                if (res.code) {
                    if (res.code === 2 && res.line) {
                        var q = $('form.i18n textarea[name="q"]').val();
                        var to = $('form.i18n textarea[name="to"]').val();
                        if (q.length <= 0) return layer.msg('{$localize.fetch_source_data}', { icon: 2 });
                        var qArr = q.split("\n");
                        var toArr = to.split("\n");
                        for (var i = 0; i < qArr.length; i++) {
                            if (!toArr[i]) {
                                var strollTo = $('form.i18n textarea[name="q"]')[0].scrollHeight;
                                $('form.i18n textarea[name="q"], form.i18n textarea[name="to"]').stop().animate({
                                    scrollTop: Math.max(strollTo * i / (qArr.length - 1) - 61.8, 0)
                                });
                                var str = qArr.slice(0, i).join("\n");
                                setSelectedText($('form.i18n textarea[name="q"]')[0], str.length + (i ? 1 : 0), str.length + qArr[i].length + (i ? 1 : 0));
                                break;
                            }
                        }
                        return layer.msg('{$localize.fetch_no_empty_line}');
                    }
                    return layer.msg(res.msg, { icon: 2 });
                }
                layer.msg(res.msg, { title: '{$localize.info}', icon: 1, btn: ['{$localize.ok}'] }, function () {
                    // 自动写入
                    if (localStorage.getItem('autoWriteDb') == 1 && $('form select[lay-filter="i18nsltl"]').length) {
                        var curr = $('form select[name="tl"]').siblings('div.layui-form-select').find('dl').find('dd[class="layui-this"]');
                        if (curr.next().length) {
                            if (curr.next().attr('lay-value').match(/^zh-/)) {
                                curr.next().next().trigger('click');
                            } else {
                                curr.next().trigger('click');
                            }
                            setTimeout(auto_write_to, 2000);
                        }
                    }
                });
            }, 'json');
            return false;
        });

        // 国际化语言框跳转
        form.on('select(i18nlang)', function (data) {
            var id = $(data.elem).data('id');
            var tlang = $(data.elem).children('option:selected').val();
            location.href = site_url + '/' + lang + '/' + module + '/' + controller + '/' + action + '/' + id + '.html?tlang=' + tlang;
        });

        // 工具事件
        util.event('lay-active', {
            // 谷歌翻译
            googleTranslate: function (othis) {
                var q = $.trim($('form.i18n textarea[name="q"]').val());
                if (q.length === 0) return $('form.i18n textarea[name="q"]').focus();
                var loading = layer.load(2);
                $.ajax({
                    url: translate_api,
                    type: 'post',
                    dataType: 'json',
                    data: {
                        client: 'gtx',
                        dt: 't',
                        dj: 1,
                        ie: 'UTF-8',
                        oe: 'UTF-8',
                        sl: $('form.i18n select[name="sl"] option:selected').val(),
                        tl: $('form.i18n select[name="tl"] option:selected').val(),
                        q: q,
                        tk: getTk(q),
                    },
                    success: function (res) {
                        layer.close(loading);
                        if (res && res.sentences) {
                            var str = $.map(res.sentences, function (el) {
                                return el.trans;
                            }).join("");
                            $('form.i18n textarea[name="to"]').val(str);
                            $('form.i18n textarea[name="to"]').next('.layui-word-aux').text('{$localize.lines}' + ' ' + str.split("\n").length);
                        }
                    },
                    error: function (XMLHttpRequest, textStatus) {
                        layer.close(loading);
                        layer.msg(textStatus + ': ' + XMLHttpRequest.status, { icon: 2 });
                    },
                });
            },

            // 填充空行
            select_fill: function (othis) {
                var q = getSelectedText($('form.i18n textarea[name="q"]')[0]);
                if (!q) return layer.msg('{$localize.select_none}', { icon: 2 });
                var qArr = $('form.i18n textarea[name="q"]').val().split("\n");
                var qIndex = qArr.indexOf(q);
                if (qIndex === -1) return layer.msg('{$localize.select_err}', { icon: 2 });
                var toArr = $('form.i18n textarea[name="to"]').val().split("\n");
                var t = toArr[qIndex];
                if (t == undefined || t.length > 0) return layer.msg('{$localize.select_line_err}', { icon: 2 });
                var loading = layer.load(2);
                $.post(site_url + '/' + lang + '/' + module + '/' + controller + '/fetch.html', {
                    tl: $('form.i18n select[name="tl"] option:selected').val()
                }, function (res) {
                    if (res.code) {
                        layer.close(loading);
                        return layer.msg(res.msg, { icon: 2 });
                    }
                    if ($('form.i18n textarea[name="q"]').val() !== res.data) {
                        layer.close(loading);
                        return layer.msg('{$localize.source_data_changed}', { icon: 2 });
                    }
                    $.ajax({
                        url: translate_api,
                        type: 'post',
                        dataType: 'json',
                        data: {
                            client: 'gtx',
                            dt: 't',
                            dj: 1,
                            ie: 'UTF-8',
                            oe: 'UTF-8',
                            sl: $('form.i18n select[name="sl"] option:selected').val(),
                            tl: $('form.i18n select[name="tl"] option:selected').val(),
                            q: q,
                            tk: getTk(q),
                        },
                        success: function (res) {
                            layer.close(loading);
                            if (res && res.sentences) {
                                var tran = $.map(res.sentences, function (el) {
                                    return el.trans;
                                }).join("");
                                toArr[qIndex] = tran;
                                $('form.i18n textarea[name="to"]').val(toArr.join("\n"));
                                var str = toArr.slice(0, qIndex).join("\n");
                                setSelectedText($('form.i18n textarea[name="to"]')[0], str.length + (qIndex ? 1 : 0), str.length + toArr[qIndex].length + (qIndex ? 1 : 0));
                                layer.msg('{$localize.fill_success}' + ' ' + (qIndex + 1), { icon: 1 });
                            }
                        },
                        error: function (XMLHttpRequest, textStatus) {
                            layer.close(loading);
                            layer.msg(textStatus + ': ' + XMLHttpRequest.status, { icon: 2 });
                        },
                    });
                }, 'json');
            },

            // 定位空行
            pos_empty_line: function (othis) {
                var q = $('form.i18n textarea[name="q"]').val();
                var to = $('form.i18n textarea[name="to"]').val();
                if (q.length <= 0) return layer.msg('{$localize.fetch_source_data}', { icon: 2 });
                var qArr = q.split("\n");
                var toArr = to.split("\n");
                for (var i = 0; i < qArr.length; i++) {
                    if (!toArr[i]) {
                        var strollTo = $('form.i18n textarea[name="q"]')[0].scrollHeight;
                        $('form.i18n textarea[name="q"], form.i18n textarea[name="to"]').stop().animate({
                            scrollTop: Math.max(strollTo * i / (qArr.length - 1) - 61.8, 0)
                        });
                        var str = qArr.slice(0, i).join("\n");
                        setSelectedText($('form.i18n textarea[name="q"]')[0], str.length + (i ? 1 : 0), str.length + qArr[i].length + (i ? 1 : 0));
                        return false;
                    }
                }
                layer.msg('{$localize.fetch_no_empty_line}');
            },

            // 行工具国际化跳转
            i18n_jump: function (othis) {
                if (!othis.data('row-slug')) return layer.msg('{$localize.i18n_slug_empty}', { icon: 2 });
                var _ta = window, parentIndex = parent.layer.getFrameIndex(window.name);
                if (typeof parentIndex !== 'undefined') {
                    parent.layer.close(parentIndex);
                    _ta = parent.window;
                }
                _ta.location.href = site_url + '/' + lang + '/' + module + '/' + controller + '/' + action.replace(/_help$/g, '_i18n') + '/' + othis.data('id') + '.html?tlang=' + othis.data('slug');
            },

            // 国际化表单返回
            i18n_back: function (othis) {
                location.href = site_url + '/' + lang + '/' + module + '/' + controller + '/' + action.replace(/_i18n$/g, '') + '.html';
            },
        });

        // 语音朗读
        var stopped = true;
        var audio = null;
        var audioArray = [];
        var textArray = [];
        var ttsArr = [];
        var ttsName = '';
        var playErrors = 0;
        var playErrorTimer = null;
        $('form.i18n .speak-voice').on('click', '.layui-icon-speaker', playStartHander);
        $('form.i18n .speak-voice').on('click', '.layui-icon-mute', playStopHander);
        $('form.i18n .speak-voice').on('click', '.layui-icon-play', playContinueHander);
        $('form.i18n .speak-voice').on('click', '.layui-icon-pause', playPauseHander);

        // 播放开始
        function playStartHander() {
            var obj = $(this).parent().parent().parent().prev().find('textarea[name]'), nodes = [];
            audio = new Audio();
            audioArray = [];
            textArray = [];
            ttsArr = obj.val().split("\n");
            ttsName = obj.attr('name');
            for (var i = 0; i < ttsArr.length; i++) {
                if ($.trim(ttsArr[i]) !== '') {
                    nodes.push({ node: ttsArr[i], index: i });
                }
            }
            if (nodes.length < 1) {
                $('textarea[name="' + ttsName + '"]').focus();
                return layer.msg('{$localize.no_voice_text}');
            }
            var voice = '';
            var slug = 'auto';
            if (ttsName == 'q') {
                voice = $('form.i18n select[name="sl"] option:selected').data('voice');
                slug = $('form.i18n select[name="sl"] option:selected').val();
            } else if (ttsName == 'to') {
                voice = $('form.i18n select[name="tl"] option:selected').data('voice');
                slug = $('form.i18n select[name="tl"] option:selected').val();
            }
            if (slug == 'auto') return layer.msg('{$localize.select_voice_lang}');
            if (voice == '') return layer.msg('{$localize.no_voice_support}');
            $(this).addClass('layui-icon-mute').removeClass('layui-icon-speaker layui-btn-primary');
            $(this).parent().append('<button type="button" class="layui-btn layui-btn-xs layui-btn-radius layui-icon layui-icon-pause"></button>');
            $('<meta name="referrer" content="same-origin">').appendTo('head').remove();
            var api = 'https://translate.google.com/translate_tts?client=gtx&ie=UTF-8&oe=UTF-8&tl=' + voice + '&q=';
            if (stopped) {
                var num = 200;
                for (var i = 0; i < nodes.length; i++) {
                    var arrs = nodes[i].node.split(/(\r\n|\r|\n)/g);
                    for (var j = 0; j < arrs.length; j++) {
                        var aAudioText = arrs[j].trim();
                        if (aAudioText) {
                            while (aAudioText.length >= num) {
                                var arr = [];
                                for (var k in aAudioText) {
                                    arr.push(aAudioText[k]);
                                    if (arr.join('').length >= num) {
                                        arr.pop();
                                        break;
                                    }
                                }
                                var pos = arr.join('').length;
                                textArray.push({ text: aAudioText.slice(0, pos), index: nodes[i].index });
                                aAudioText = aAudioText.slice(pos);
                            }
                        }
                        aAudioText && textArray.push({ text: aAudioText, index: nodes[i].index });
                    }
                }
                for (var i = 0; i < textArray.length; i++) {
                    var address = api + encodeURIComponent(textArray[i].text) + '&tk=' + getTk(textArray[i].text);
                    audioArray.unshift(address);
                }
                audio.preload = true;
                audio.controls = true;
                audio.src = audioArray.pop();
                audio.addEventListener('ended', playEndedHandler);
                audio.addEventListener('error', playErrorHandler);
                audio.loop = false;
                audio.play();
                stopped = false;
                var reader = textArray.shift();
                var str = ttsArr.slice(0, reader.index).join("\n");
                var strollTo = $('form.i18n textarea[name="' + ttsName + '"]')[0].scrollHeight;
                $('form.i18n textarea[name="' + ttsName + '"]').stop().animate({
                    scrollTop: Math.max(strollTo * reader.index / (ttsArr.length - 1) - 61.8, 0)
                });
                setSelectedText($('form.i18n textarea[name="' + ttsName + '"]')[0], str.length + (reader.index ? 1 : 0), str.length + (reader.index ? 1 : 0) + ttsArr[reader.index].length);
            } else {
                audio.play();
            }
        }

        // 继续播放
        function playContinueHander() {
            $('form.i18n .speak-voice').children('button.layui-icon-play').addClass('layui-icon-pause').removeClass('layui-icon-play');
            audio.play();
        }

        // 播放暂停
        function playPauseHander() {
            $('form.i18n .speak-voice').children('button.layui-icon-pause').addClass('layui-icon-play').removeClass('layui-icon-pause');
            audio.pause();
        }

        // 播放停止
        function playStopHander() {
            $('form.i18n .speak-voice').children('button.layui-icon-play').remove();
            $('form.i18n .speak-voice').children('button.layui-icon-pause').remove();
            $('form.i18n .speak-voice').children('button.layui-icon-mute').addClass('layui-icon-speaker layui-btn-primary').removeClass('layui-icon-mute');
            audio.pause();
            audio.removeEventListener('ended', playEndedHandler);
            audio.removeEventListener('error', playErrorHandler);
            audioArray = [];
            stopped = true;
            textArray = [];
        }

        // 播放结束处理
        function playEndedHandler() {
            playErrors = 0;
            if (textArray.length > 0) {
                audio.src = audioArray.pop();
                audio.play();
                var reader = textArray.shift();
                var str = ttsArr.slice(0, reader.index).join("\n");
                var strollTo = $('form.i18n textarea[name="' + ttsName + '"]')[0].scrollHeight;
                $('form.i18n textarea[name="' + ttsName + '"]').stop().animate({
                    scrollTop: Math.max(strollTo * reader.index / (ttsArr.length - 1) - 61.8, 0)
                });
                setSelectedText($('form.i18n textarea[name="' + ttsName + '"]')[0], str.length + (reader.index ? 1 : 0), str.length + (reader.index ? 1 : 0) + ttsArr[reader.index].length);
            } else {
                playStopHander();
                layer.msg('{$localize.voice_reading_finished}', { icon: 1 });
            }
        }

        // 播放错误处理
        function playErrorHandler() {
            playErrorTimer && clearTimeout(playErrorTimer);
            playErrorTimer = setTimeout(function () {
                if (playErrors % 10 < 9) {
                    playErrors++;
                    audio.src = audio.src.split('&random=')[0] + '&random=' + new Date().getTime();
                    audio.play();
                } else {
                    clearTimeout(playErrorTimer);
                    playErrorTimer = null;
                    playErrors = 0;
                    playStopHander();
                    layer.alert('Audio error code: ' + audio.error.code, { title: '{$localize.info}', icon: 2, btn: ['{$localize.ok}'] });
                }
            }, 3000 + Math.ceil(Math.random() * 2000));
        }

        // 发送翻译（分离标签文本和属性）
        function send_translate(html) {
            var txts = html.split(/<[^>]*>/) || [];
            var tags = html.match(/<[^>]*>/g) || [];
            var match = null;
            var regex = /\b(title|alt|placeholder)\s*=\s*(["'])([^"']+)\2/gi;
            for (var i = 0; i < tags.length; i++) {
                while ((match = regex.exec(tags[i])) !== null) {
                    txts.push(match[3]);
                }
            }
            return txts.join('\n');
        }

        // 修复翻译（合并标签文本和属性）
        function repair_translate(html, trans) {
            var obj = {
                tag: [],
                txt: [],
                len: []
            }
            var txts = html.split(/<[^>]*>/) || [];
            var tags = html.match(/<[^>]*>/g) || [];
            var match = null;
            var regex = /\b(title|alt|placeholder)\s*=\s*(["'])([^"']+)\2/gi;
            for (var i = 0; i < tags.length; i++) {
                obj.txt.push(txts[i]);
                obj.tag.push(tags[i]);
                obj.len.push(txts[i].split('\n').length);
            }
            obj.txt.push(txts[tags.length]);
            obj.len.push(txts[tags.length].split('\n').length);
            var maps = [];
            for (var i = 0; i < tags.length; i++) {
                while ((match = regex.exec(tags[i])) !== null) {
                    maps.push({ len: match[3].split('\n').length });
                }
            }
            var pos = 0;
            for (var i = 0; i < maps.length; i++) {
                pos -= maps[i].len;
            }
            var i = 0;
            var j = 0;
            var arr = [];
            var res = [];
            var lines = trans.split('\n');
            var attrs = lines.slice(pos);
            while ((arr = lines.slice(i, i + obj.len[j])).length) {
                res.push(arr.join('\n'));
                if (j < obj.tag.length) {
                    if (obj.tag[j].match(/<strong>|<span[^>]*>/)) res.push(' ');
                    obj.tag[j] = obj.tag[j].replace(regex, function (m, p1, p2, p3) {
                        var prop = [];
                        for (var r = 0; r < p3.split('\n').length; r++) {
                            prop.push(attrs.shift());
                        }
                        return p1 + '=' + p2 + prop.join(' ') + p2;
                    });
                    res.push(obj.tag[j]);
                    if (obj.tag[j].match(/<\/strong>|<\/span[^>]*>/)) res.push(' ');
                }
                i += obj.len[j];
                j++;
            }
            result = res.join('');
            result = result.replace(/(<strong>)\s+(<span[^>]*>)/gi, '$1$2');
            result = result.replace(/(<\/span>)\s+(<\/strong>)/gi, '$1$2');
            result = result.replace(/(<span[^>]*>)\s+(<strong>)/gi, '$1$2');
            result = result.replace(/(<\/strong>)\s+(<\/span>)/gi, '$1$2');
            return result;
        }

        // 翻译校验
        function chk_err() {
            var res = [];
            var _title = $('form input[name="_title"]');
            var title = $('form input[name="title"]');
            var _name = $('form input[name="_name"]');
            var name = $('form input[name="name"]');
            var _description = $('form textarea[name="_description"]');
            var description = $('form textarea[name="description"]');
            var _category = $('form select[name="_category_id"]');
            var category = $('form select[name="category_id"]');
            var _tag_ids = $('form input[class="_tag_ids"]');
            var tag_ids = $('form input[class="tag_ids"]');
            var _tags = $('form input[name="_tags"]');
            var tags = $('form input[name="tags"]');
            var _seo_title = $('form input[name="_seo_title"]');
            var seo_title = $('form input[name="seo_title"]');
            var _seo_title = $('form input[name="_seo_title"]');
            var _seo_description = $('form textarea[name="_seo_description"]');
            var seo_description = $('form textarea[name="seo_description"]');
            // 选择语言
            !$('form select[name="lang"]').val() && res.push('{$localize.please_select_language}');
            // 检查标题
            _title.val() && !title.val() && res.push('{$localize.input} -> {$localize.title}');
            // 检查名称
            _name.val() && !name.val() && res.push('{$localize.input} -> {$localize.name}');
            // 检查分类
            if (_category.children('option').length !== category.children('option').length) {
                res.push('{$localize.please_first_complete_i18n} -> {$localize.category}');
            } else {
                if (_category.children('option:selected').index() !== category.children('option:selected').index()) {
                    res.push('{$localize.choose} -> {$localize.category}');
                }
            }
            // 检查描述
            _description.val() && !description.val() && res.push('{$localize.input} -> {$localize.description}');
            // 检查内容标签
            if ('undefined' !== typeof KindEditor && window._editor1 && window.editor1) {
                !window._editor1.isEmpty() && window.editor1.isEmpty() && res.push('{$localize.editor_empty}');
                var errors = validateTags(window.editor1.html());
                while (errors.length) {
                    res.push(errors.shift());
                }
            }
            // 检查标签
            if (_tag_ids.length !== tag_ids.length) res.push('{$localize.please_first_complete_i18n} -> {$localize.tag}');
            for (var i = 0; i < _tag_ids.length; i++) {
                if ((tags.length && tags.val()) || (($(_tag_ids.eq(i)).prop('checked') && !$(tag_ids.eq(i)).prop('checked')) || (!$(_tag_ids.eq(i)).prop('checked') && $(tag_ids.eq(i)).prop('checked')))) {
                    res.push('{$localize.choose} -> {$localize.tag}');
                    break;
                }
            }
            // 检查SEO标题
            _seo_title.val() && !seo_title.val() && res.push('{$localize.input} -> SEO {$localize.title}');
            // 检查SEO描述
            _seo_description.val() && !seo_description.val() && res.push('{$localize.input} -> SEO {$localize.description}');
            return res;
        }

        // 校验内容标签
        function validateTags(html) {
            var errors = [];
            // KindEditor 允许的自闭合标签
            var selfClosingTags = ['area', 'base', 'basefont', 'br', 'col', 'frame', 'hr', 'img', 'input', 'isindex', 'link', 'meta', 'param', 'embed'];
            // 匹配所有块：成对标签块或游离的单个标签（开/闭）
            var blocks = html.match(/<([a-z]+)(?![^>]*\/>)[^>]*>[\s\S]*?<\/\1>|<\/?[a-z]+[^>]*>/gi) || [];
            for (var i = 0; i < blocks.length; i++) {
                var block = blocks[i];
                var tagStack = [];
                // 提取块内所有标签（过滤自闭合）
                var allTags = block.match(/<\/?([a-z]+)(\s+[^>]*?)?>/gi) || [];
                for (var j = 0; j < allTags.length; j++) {
                    var fullTag = allTags[j];
                    var tagNameMatch = fullTag.match(/<\/?([a-z]+)/i);
                    if (!tagNameMatch) continue;
                    var tagName = tagNameMatch[1].toLowerCase();
                    // 检测自闭合标签
                    var isSelfClosing = (/\/\s*>/.test(fullTag) || selfClosingTags.indexOf(tagName) !== -1);
                    if (isSelfClosing) continue;
                    var isClosing = fullTag.indexOf('</') === 0;
                    if (!isClosing) {
                        tagStack.push(tagName);
                    } else {
                        if (tagStack.length === 0) {
                            // 不匹配的闭标签
                            errors.push('{$localize.close_sort_error}: {$localize.found_dismatch_close_tag} &lt;/' + tagName + '&gt; - {$localize.block} ' + (i + 1));
                        } else {
                            var lastTag = tagStack.pop();
                            if (lastTag !== tagName) {
                                // 闭合标签顺序错误
                                errors.push('{$localize.close_sort_error}: {$localize.expect} &lt;/' + lastTag + '> {$localize.but_found} &lt;/' + tagName + '&gt; - {$localize.block} ' + (i + 1));
                                tagStack.push(lastTag); // 恢复堆栈
                            }
                        }
                    }
                }
                // 检测未闭合的开始标签
                if (tagStack.length > 0) {
                    errors.push('{$localize.unclosed_tag}: ' + tagStack.join(', ') + ' - {$localize.block} ' + (i + 1));
                }
            }
            return errors;
        }

        // 自动写入数据库
        if ($('form input[lay-filter="auto-db"]').length) {
            form.on('checkbox(auto-db)', function (data) {
                localStorage.setItem('autoWriteDb', data.elem.checked ? 1 : 0);
            });
            if (localStorage.getItem('autoWriteDb') == 1) {
                $('form input[lay-filter="auto-db"]').prop('checked', true);
                if ($('form select[lay-filter="i18nlang"]').length) {
                    auto_write_db()
                }
            } else {
                $('form input[lay-filter="auto-db"]').prop('checked', false);
            }
            form.render('checkbox');
        }

        // 目标语言包
        function auto_write_to() {
            $('#chk-loading').removeClass('layui-hide');
            var timeVal = 10000 + Math.ceil(Math.random() * 20000);
            setTimeout(function () {
                $('#chk-loading').addClass('layui-hide');
                $('form button[lay-active="googleTranslate"]').trigger('click');
                // 开始轮询
                var n = 0;
                var write = setInterval(function () {
                    n++;
                    var has_done = true;
                    var q = $('form.i18n textarea[name="q"]').val();
                    var to = $('form.i18n textarea[name="to"]').val();
                    if (q.length <= 0) return layer.msg('{$localize.fetch_source_data}', { icon: 2 });
                    var qArr = q.split("\n");
                    var toArr = to.split("\n");
                    for (var i = 0; i < qArr.length; i++) {
                        if (!toArr[i]) {
                            has_done = false;
                            break;
                        }
                    }
                    if (n * 2000 >= timeVal - 2000) {
                        clearInterval(write);
                        write = null;
                        layer.alert('{$localize.request_time_out}', { icon: 2 });
                    } else if (has_done) {
                        clearInterval(write);
                        write = null;
                        $('button[lay-filter="generate"]').trigger('click');
                    }
                }, 2000);
            }, timeVal);
        }

        // 分类、标签、内容、页面
        function auto_write_db() {
            var tlang = $('select[name="lang"]').val();
            if (!tlang) return false;
            var curr = $('select[name="lang"]').children('option[value="' + tlang + '"]');
            // 判断上下文
            if (curr.text().slice(-1) == '√') {
                if (tlang == 'ts') {
                    if (curr.prev().val() && curr.prev().text().slice(-1) == '√') {
                        var pos = location.href.lastIndexOf('/');
                        var nextId = parseInt($('form input[lay-filter="auto-db"]').data('next-id'));
                        var maxId = parseInt($('form input[lay-filter="auto-db"]').data('max-id'));
                        if (nextId > 0 && nextId <= maxId) {
                            location.href = location.href.slice(0, pos) + '/' + nextId + '.html?tlang=co';
                        }
                    }
                } else {
                    if (curr.next().val() == 'zh-TW' || curr.next().val() == 'zh-CN') {
                        if (curr.next().next().val() && curr.next().next().text().slice(-1) != '√') {
                            location.href = location.href.replace('?tlang=' + tlang, '?tlang=' + curr.next().next().val());
                        }
                    } else {
                        if (curr.next().val() && curr.next().text().slice(-1) != '√') {
                            location.href = location.href.replace('?tlang=' + tlang, '?tlang=' + curr.next().val());
                        }
                    }
                }
            } else {
                $('#chk-loading').removeClass('layui-hide');
                $('html, body').animate({ scrollTop: 0 }, 500);
                var timeVal = 10000 + Math.ceil(Math.random() * 20000);
                setTimeout(function () {
                    $('#chk-loading').addClass('layui-hide');
                    $('form .fill-translate').trigger('click');
                    // 开始轮询
                    var n = 0;
                    var write = setInterval(function () {
                        n++;
                        var _title = $('form input[name="_title"]');
                        var title = $('form input[name="title"]');
                        var _name = $('form input[name="_name"]');
                        var name = $('form input[name="name"]');
                        var _category = $('form select[name="_category_id"]');
                        var category = $('form select[name="category_id"]');
                        var _tag_ids = $('form input[class="_tag_ids"]');
                        var tag_ids = $('form input[class="tag_ids"]');
                        var _tags = $('form input[name="_tags"]');
                        var tags = $('form input[name="tags"]');
                        var has_done = (name.length && name.val()) || (title.length && title.val());
                        if (n * 2000 >= timeVal - 2000) {
                            clearInterval(write);
                            write = null;
                            layer.alert('{$localize.request_time_out}', { icon: 2 });
                        } else if (has_done) {
                            clearInterval(write);
                            write = null;
                            // 尝试修复分类和标签错误
                            if (_category.length && category.length && _category.children('option').length === category.children('option').length) {
                                if (_category.children('option:selected').index() !== category.children('option:selected').index()) {
                                    var selectIndex = _category.children('option:selected').index();
                                    if (category.siblings('div.layui-form-select').length) {
                                        category.siblings('div.layui-form-select').find('dl').find('dd').eq(selectIndex).trigger('click');
                                    }
                                }
                            }
                            if (_tag_ids.length && tag_ids.length && _tag_ids.length === tag_ids.length) {
                                for (var i = 0; i < _tag_ids.length; i++) {
                                    if ($(_tag_ids.eq(i)).prop('checked') !== $(tag_ids.eq(i)).next('div.layui-form-checkbox').hasClass('layui-form-checked')) {
                                        $(tag_ids.eq(i)).next('div.layui-form-checkbox').trigger('click');
                                    }
                                }
                            }
                            if (_tag_ids.length && tag_ids.length && _tag_ids.length === tag_ids.length && _tags.length && tags.length && tags.val()) {
                                tags.val('');
                            }
                            // 检查是否还有错误
                            var err = chk_err();
                            if (err.length) {
                                layer.alert(err.shift(), { icon: 2 });
                            } else {
                                if ($('.ke-container .ke-toolbar .ke-outline.ke-selected .ke-icon-source').length) {
                                    $('.ke-container .ke-toolbar .ke-outline.ke-selected .ke-icon-source').trigger('click');
                                }
                                $('html, body').animate({ scrollTop: $(document).height() - $(window).height() }, 500);
                                setTimeout(function () {
                                    $('button[lay-filter="submit"]').trigger('click');
                                }, 1000);
                            }
                        }
                    }, 2000);
                }, timeVal);
            }
        }

        // 国际化翻译
        $('form .i18n-tran').click(function () {
            var rawHTML = '';
            var slop = $(this).parent().parent().parent().find('.i18n-sl');
            var tlop = $(this).parent().parent().parent().find('.i18n-tl');
            var tlang = $(this).parent().parent().parent().parent().parent().find('.i18n-lang').val();
            if (!tlang) return layer.msg('{$localize.please_select_language}', { icon: 2 });
            var qArr = [];
            var loading = layer.load(2);
            if (slop.children('option').length) {
                qArr.push(slop.children('option:selected').text().replace(/\s*┠\s*/, '').trim());
            } else if (slop.children('input[type="checkbox"]').length) {
                qArr.push(slop.children('input[type="checkbox"]:checked').map(function () {
                    return $(this).attr('title').trim();
                }).get().join('\n'));
            } else if (slop.hasClass('ke-editor') && window._editor1) {
                rawHTML = window._editor1.html();
                qArr.push('.');
                qArr.push(send_translate(rawHTML));
            } else {
                qArr.push(slop.val().trim());
            }
            $.ajax({
                url: translate_api,
                type: 'post',
                dataType: 'json',
                data: {
                    client: 'gtx',
                    dt: 't',
                    dj: 1,
                    ie: 'UTF-8',
                    oe: 'UTF-8',
                    sl: 'zh-CN',
                    tl: tlang,
                    tk: getTk(qArr.join('\n')),
                    q: qArr.join('\n')
                },
                success: function (res) {
                    layer.close(loading);
                    if (res && res.sentences) {
                        var resText = $.map(res.sentences, function (el) {
                            return el.trans;
                        }).join('');
                        if (!tlop.hasClass('ke-editor')) {
                            resText = resText.replace(/"/g, '');
                        }
                        if (tlop.children('option').length) {
                            var selected = tlop.children('option:contains("' + resText + '")').val();
                            if (selected) {
                                tlop.siblings('div.layui-form-select').find('dl').find('dd[lay-value="' + selected + '"]').trigger('click');
                            } else if (slop.children('option').length === tlop.children('option').length) {
                                var selectIndex = slop.children('option:selected').index();
                                tlop.siblings('div.layui-form-select').find('dl').find('dd').eq(selectIndex).trigger('click');
                            }
                        } else if (tlop.children('input[type="checkbox"]').length) {
                            var resArr = resText.split('\n');
                            var inputText = '';
                            while (resArr.length) {
                                var item = resArr.shift().trim();
                                if (tlop.children('input[title="' + item + '"]').length) {
                                    tlop.children('input[title="' + item + '"]').each(function () {
                                        if (!$(this).next('div.layui-form-checkbox').hasClass('layui-form-checked')) {
                                            $(this).next('div.layui-form-checkbox').trigger('click');
                                        }
                                    });
                                } else {
                                    if (inputText) {
                                        inputText += ',';
                                    }
                                    inputText += ('' + item).replace(/\,/g, '');
                                }
                            }
                            if (slop.children('input[type="checkbox"]').length === tlop.children('input[type="checkbox"]').length && inputText) {
                                var schks = slop.children('input[type="checkbox"]');
                                var tchks = tlop.children('input[type="checkbox"]');
                                for (var i = 0; i < schks.length; i++) {
                                    if ($(schks.eq(i)).prop('checked') !== $(tchks.eq(i)).next('div.layui-form-checkbox').hasClass('layui-form-checked')) {
                                        $(tchks.eq(i)).next('div.layui-form-checkbox').trigger('click');
                                    }
                                }
                                tlop.parent().parent().find('input[type="text"]').val('');
                            } else {
                                tlop.parent().parent().find('input[type="text"]').val(inputText);
                            }
                        } else if (tlop.hasClass('ke-editor') && window.editor1) {
                            window.editor1.html(repair_translate(rawHTML, resText.split('\n').slice(1).join('\n')));
                        } else {
                            if (tlop.attr('name') == 'tags') {
                                tlop.val(('' + resText).replace(/\,/g, '').split('\n').join(','));
                            } else {
                                tlop.val(resText);
                            }
                        }
                    }
                },
                error: function (XMLHttpRequest, textStatus) {
                    layer.close(loading);
                    layer.msg(textStatus + ': ' + XMLHttpRequest.status, { icon: 2 });
                },
            });
        });

        // 一键填充翻译
        $('form .fill-translate').click(function () {
            var tlang = $(this).parent().parent().find('.i18n-lang').val();
            var arr = [];
            var rawHTML = '';
            if (!tlang) return layer.msg('{$localize.please_select_language}', { icon: 2 });
            $('form .i18n-tran').each(function (i, elem) {
                var slop = $(elem).parent().parent().parent().find('.i18n-sl');
                var tlop = $(elem).parent().parent().parent().find('.i18n-tl');
                arr.push({ slop: slop, tlop: tlop })
            });
            var loading = layer.load(2);
            var qArr = [];
            $.each(arr, function (i, obj) {
                if (obj.slop.children('option').length) {
                    qArr.push(obj.slop.children('option:selected').text().replace(/\s*┠\s*/, '').trim());
                } else if (obj.slop.children('input[type="checkbox"]').length) {
                    qArr.push(obj.slop.children('input[type="checkbox"]:checked').map(function () {
                        return $(this).attr('title').trim();
                    }).get().join('\n'));
                } else if (obj.slop.hasClass('ke-editor') && window._editor1) {
                    rawHTML = window._editor1.html();
                    qArr.push(send_translate(rawHTML));
                } else {
                    qArr.push(obj.slop.val().trim());
                }
            });
            $.ajax({
                url: translate_api,
                type: 'post',
                dataType: 'json',
                data: {
                    client: 'gtx',
                    dt: 't',
                    dj: 1,
                    ie: 'UTF-8',
                    oe: 'UTF-8',
                    sl: 'zh-CN',
                    tl: tlang,
                    tk: getTk(qArr.join('\n')),
                    q: qArr.join('\n')
                },
                success: function (res) {
                    layer.close(loading);
                    if (res && res.sentences) {
                        var resTexts = $.map(res.sentences, function (el) {
                            return el.trans;
                        }).join('');
                        var resArrs = resTexts.split('\n');
                        $.each(arr, function (i, obj) {
                            var unitArr = [];
                            for (var j = 0; j < qArr[i].split('\n').length; j++) {
                                unitArr.push(resArrs.shift());
                            }
                            var resText = unitArr.join('\n');
                            if (!obj.tlop.hasClass('ke-editor')) {
                                resText = resText.replace(/"/g, '');
                            }
                            if (obj.tlop.children('option').length) {
                                var selected = obj.tlop.children('option:contains("' + resText + '")').val();
                                if (selected) {
                                    obj.tlop.siblings('div.layui-form-select').find('dl').find('dd[lay-value="' + selected + '"]').trigger('click');
                                } else if (obj.slop.children('option').length === obj.tlop.children('option').length) {
                                    var selectIndex = obj.slop.children('option:selected').index();
                                    obj.tlop.siblings('div.layui-form-select').find('dl').find('dd').eq(selectIndex).trigger('click');
                                }
                            } else if (obj.tlop.children('input[type="checkbox"]').length) {
                                var resArr = resText.split('\n');
                                var inputText = '';
                                while (resArr.length) {
                                    var item = resArr.shift().trim();
                                    if (obj.tlop.children('input[title="' + item + '"]').length) {
                                        obj.tlop.children('input[title="' + item + '"]').each(function () {
                                            if (!$(this).next('div.layui-form-checkbox').hasClass('layui-form-checked')) {
                                                $(this).next('div.layui-form-checkbox').trigger('click');
                                            }
                                        });
                                    } else {
                                        if (inputText) {
                                            inputText += ',';
                                        }
                                        inputText += ('' + item).replace(/\,/g, '');
                                    }
                                }
                                if (obj.slop.children('input[type="checkbox"]').length === obj.tlop.children('input[type="checkbox"]').length && inputText) {
                                    var schks = obj.slop.children('input[type="checkbox"]');
                                    var tchks = obj.tlop.children('input[type="checkbox"]');
                                    for (var i = 0; i < schks.length; i++) {
                                        if ($(schks.eq(i)).prop('checked') !== $(tchks.eq(i)).next('div.layui-form-checkbox').hasClass('layui-form-checked')) {
                                            $(tchks.eq(i)).next('div.layui-form-checkbox').trigger('click');
                                        }
                                    }
                                    obj.tlop.parent().parent().find('input[type="text"]').val('');
                                } else {
                                    obj.tlop.parent().parent().find('input[type="text"]').val(inputText);
                                }
                            } else if (obj.tlop.hasClass('ke-editor') && window.editor1) {
                                window.editor1.html(repair_translate(rawHTML, resText));
                            } else {
                                if (obj.tlop.attr('name') == 'tags') {
                                    obj.tlop.val(('' + resText).replace(/\,/g, '').split('\n').join(','));
                                } else {
                                    obj.tlop.val(resText);
                                }
                            }
                        });
                    }
                },
                error: function (XMLHttpRequest, textStatus) {
                    layer.close(loading);
                    layer.msg(textStatus + ': ' + XMLHttpRequest.status, { icon: 2 });
                },
            });
        });

        // 别名翻译
        $('form .translate-slug').click(function () {
            var _this = $(this);
            var title = $('form input[name="title"], form input[name="name"]');
            var slugField = $('form input[name="slug"]');
            if (title.val().trim() == '') return layer.msg('{$localize.untitled}', { icon: 2 });
            if ('Pinyin' in window && window.Pinyin.isSupported() && 'navigator' in window && !window.navigator.onLine) {
                // 离线转拼音
                var pinyin = '';
                var tokens = Pinyin.parse(title.val().trim());
                var lastToken;
                tokens.forEach(function (v, i) {
                    if (v.type === 2) {
                        var formatTarget = v.target ? v.target.toLowerCase() : '';
                        pinyin += pinyin && !/\n|\s/.test(lastToken.target) ? ' ' + formatTarget : formatTarget;
                    } else {
                        pinyin += (lastToken && lastToken.type === 2 ? ' ' : '') + v.target;
                    }
                    lastToken = v;
                });
                slugField.val(pinyin);
            } else {
                // 否则使用接口（需联网）转英语
                icon = new Image();
                icon.src = 'https://www.google.com/favicon.ico?t=' + new Date().getTime();
                _this.addClass('layui-btn-disabled').attr('disabled', true).parent().find('.loading').removeClass('layui-hide');
                var timer = setTimeout(function () {
                    icon.onerror = icon.onload = null;
                    baidu_translate();
                }, 3000);
                icon.onerror = function () {
                    clearTimeout(timer);
                    timer = null;
                    baidu_translate();
                }
                icon.onload = function () {
                    clearTimeout(timer);
                    timer = null;
                    google_translate();
                }
                // 谷歌翻译
                function google_translate() {
                    $.ajax({
                        url: 'https://translate.googleapis.com/translate_a/single',
                        type: 'post',
                        dataType: 'json',
                        data: {
                            client: 'webapp',
                            dt: 't',
                            dj: 1,
                            ie: 'UTF-8',
                            oe: 'UTF-8',
                            sl: 'zh-CN',
                            tl: 'en',
                            tk: getTk(title.val().trim()),
                            q: title.val().trim()
                        },
                        success: function (res) {
                            _this.removeClass('layui-btn-disabled').attr('disabled', false).parent().find('.loading').addClass('layui-hide');
                            if (res && res.sentences) {
                                slugField.val($.map(res.sentences, function (el) {
                                    return el.trans.replace(/[\W]/g, ' ');
                                }).join(' ').replace(/\s+/g, ' ').trim());
                            }
                        },
                        error: function (XMLHttpRequest, textStatus) {
                            _this.removeClass('layui-btn-disabled').attr('disabled', false).parent().find('.loading').addClass('layui-hide');
                            layer.msg(textStatus + ': ' + XMLHttpRequest.status, { icon: 2 });
                        },
                    });
                }
                // 百度翻译
                function baidu_translate() {
                    $.ajax({
                        url: site_url + '/api/baidu_translate',
                        type: 'post',
                        dataType: 'json',
                        data: {
                            query: title.val().trim(),
                            from: 'zh',
                            to: 'en',
                            transtype: 'translang',
                            simple_means_flag: 3,
                            sign: getTk(title.val().trim(), 1),
                            token: '853eba4bc7ac9601ef8fff761c7cf8cf',
                        },
                        success: function (res) {
                            _this.removeClass('layui-btn-disabled').attr('disabled', false).parent().find('.loading').addClass('layui-hide');
                            if (res && res.trans_result && res.trans_result.data) {
                                slugField.val($.map(res.trans_result.data, function (el) {
                                    return el.dst.replace(/[\W]/g, ' ');
                                }).join(' ').replace(/\s+/g, ' ').trim());
                            }
                        },
                        error: function (XMLHttpRequest, textStatus) {
                            _this.removeClass('layui-btn-disabled').attr('disabled', false).parent().find('.loading').addClass('layui-hide');
                            layer.msg(textStatus + ': ' + XMLHttpRequest.status, { icon: 2 });
                        },
                    });
                }
                // 谷歌代理
                function proxy_translate() {
                    $.ajax({
                        url: 'https://api.translate.zvo.cn/translate.json',
                        type: 'post',
                        dataType: 'json',
                        data: {
                            from: 'chinese_simplified',
                            to: 'english',
                            text: JSON.stringify([title.val().trim()])
                        },
                        beforeSend: function () {
                            _this.addClass('layui-btn-disabled').attr('disabled', true).parent().find('.loading').removeClass('layui-hide');
                        },
                        success: function (res) {
                            _this.removeClass('layui-btn-disabled').attr('disabled', false).parent().find('.loading').addClass('layui-hide');
                            if (res && res.result) {
                                slugField.val(res.text.join(' ').replace(/[\W]/g, ' ').replace(/\s+/g, ' ').trim());
                            }
                        },
                        error: function (XMLHttpRequest, textStatus) {
                            _this.removeClass('layui-btn-disabled').attr('disabled', false).parent().find('.loading').addClass('layui-hide');
                            layer.msg(textStatus + ': ' + XMLHttpRequest.status, { icon: 2 });
                        },
                    });
                }
            }
        });

        // 字数统计
        var characters_count = function () {
            if ($('form .characters-count').length) {
                $('form .characters-count').each(function (i, elem) {
                    if ($(elem).prev().val().trim().length) {
                        var str = $(elem).prev().val().trim();
                        var len = str.length;
                        for (var j in str) {
                            if (str[j].charCodeAt(0).toString(16).length == 4) len += 1;
                        }
                        $(elem).html('<span style="color:#f00;font-weight:bold">' + len + '</span> ( ≤ ' + (i == 0 ? '60' : '140') + ' characters)');
                    } else {
                        $(elem).html('');
                    }
                });
            }
        }
        characters_count();
        $('form input[name="seo_title"], form textarea[name="seo_description"]').on('keyup change', characters_count);

        // Baidu 关键词建议
        window.bdsug = {
            sug: function (data) {
                $('form .keywords-suggest.baidu').removeClass('layui-btn-disabled').attr('disabled', false).parent().find('.loading').addClass('layui-hide');
                if (data && data.s.length) {
                    var arr = [];
                    for (var i = 0; i < data.s.length; i++) {
                        arr.push('<button type="button" class="layui-btn layui-btn-primary layui-btn-sm suggest-item">' + data.s[i] + '</button>');
                    }
                    $('form .keywords-suggest.baidu').parent().parent().find('.suggest-result').addClass('layui-input-block').html('<fieldset class="layui-elem-field"><div class="layui-field-box">' + arr.join('\n') + '</div></fieldset>');
                } else {
                    $('form .keywords-suggest.baidu').parent().parent().find('.suggest-result').removeClass('layui-input-block').html('');
                }
            }
        }

        // Google 关键词建议
        window.google = {
            ac: {
                h: function (data) {
                    $('form .keywords-suggest.google').removeClass('layui-btn-disabled').attr('disabled', false).parent().find('.loading').addClass('layui-hide');
                    if (data && data[1].length) {
                        var arr = [];
                        for (var i = 0; i < data[1].length; i++) {
                            arr.push('<button type="button" class="layui-btn layui-btn-primary layui-btn-sm suggest-item">' + data[1][i][0] + '</button>');
                        }
                        $('form .keywords-suggest.google').parent().parent().find('.suggest-result').addClass('layui-input-block').html('<fieldset class="layui-elem-field"><div class="layui-field-box">' + arr.join('\n') + '</div></fieldset>');
                    } else {
                        $('form .keywords-suggest.google').parent().parent().find('.suggest-result').removeClass('layui-input-block').html('');
                    }
                }
            }
        }

        // 关键词建议
        $('form .keywords-suggest').click(function () {
            var word = $('form input[name="title"], form input[name="name"], form input[name="webName"]').val().trim();
            if (word == '') return layer.msg('{$localize.untitled}', { icon: 2 });
            $(this).parent().parent().find('.suggest-result').removeClass('layui-input-block').html('')
            $(this).addClass('layui-btn-disabled').attr('disabled', true).parent().find('.loading').removeClass('layui-hide');
            // 百度关键字建议
            if ($(this).hasClass('baidu')) {
                $.ajax({
                    url: 'https://suggestion.baidu.com/su',
                    type: 'get',
                    dataType: 'jsonp',
                    timeout: 5000,
                    data: {
                        wd: word,
                        ie: 'UTF-8',
                        cb: 'window.bdsug.sug'
                    },
                    error: function (XMLHttpRequest, textStatus) {
                        $('form .keywords-suggest').removeClass('layui-btn-disabled').attr('disabled', false).parent().find('.loading').addClass('layui-hide');
                    },
                });
            }
            // 谷歌关键字建议
            if ($(this).hasClass('google')) {
                $.ajax({
                    url: suggest_api,
                    type: 'get',
                    dataType: 'jsonp',
                    data: {
                        hl: lang,
                        client: 'youtube',
                        q: word,
                        ie: 'UTF-8',
                        jsonp: 'window.google.ac.h'
                    },
                    error: function (XMLHttpRequest, textStatus) {
                        $('form .keywords-suggest').removeClass('layui-btn-disabled').attr('disabled', false).parent().find('.loading').addClass('layui-hide');
                    },
                });
            }
        });

        // 关键词建议结果
        $('form .suggest-result').on('click', '.suggest-item', function () {
            var title = $('form input[name="seo_title"]');
            var discription = $('form textarea[name="seo_description"]');
            if (title.val().trim()) {
                title.val(title.val().trim() + '-');
            }
            title.val(title.val().trim() + $(this).text());
            if (discription.val().trim()) {
                discription.val(discription.val().trim() + (lang.match(/^zh-/) ? '，' : ','));
            }
            discription.val(discription.val().trim() + $(this).text());
            $(this).addClass('layui-btn-disabled').attr('disabled', true);
            characters_count();
        });

        // 获取选中文本
        function getSelectedText(inputDom) {
            if (window.getSelection) {
                if (inputDom.selectionStart != undefined && inputDom.selectionEnd != undefined) {
                    return inputDom.value.substring(inputDom.selectionStart, inputDom.selectionEnd);
                } else {
                    return "";
                }
            } else if (document.selection) {
                return document.selection.createRange().text;
            } else {
                return "";
            }
        }

        // 设置选中的文本高亮
        function setSelectedText(inputDom, startIndex, endIndex) {
            if (inputDom.setSelectionRange) {
                inputDom.setSelectionRange(startIndex, endIndex);
            } else if (inputDom.createTextRange) {
                var range = inputDom.createTextRange();
                range.collapse(true);
                range.moveStart('character', startIndex);
                range.moveEnd('character', endIndex - startIndex - 1);
                range.select();
            }
            inputDom.focus();
        }

        // 谷歌百度翻译tk算法
        function getTk(a, t) {
            var gtk = t ? '320305.131321201' : '406398.2087938574';
            var e = gtk.split('.'), h = Number(e[0]) || 0, g = [], d = 0, i, j;
            for (var f = 0; f < a.length; f++) {
                var c = a.charCodeAt(f);
                128 > c ? g[d++] = c : (2048 > c ? g[d++] = c >> 6 | 192 : (55296 == (c & 64512) && f + 1 < a.length && 56320 == (a.charCodeAt(f + 1) & 64512) ? (c = 65536 + ((c & 1023) << 10) + (a.charCodeAt(++f) & 1023), g[d++] = c >> 18 | 240, g[d++] = c >> 12 & 63 | 128) : g[d++] = c >> 12 | 224, g[d++] = c >> 6 & 63 | 128), g[d++] = c & 63 | 128)
            }
            a = h;
            for (var d = 0; d < g.length; d++) {
                a += g[d];
                i = '+-a^+6';
                for (var k = 0; k < i.length - 2; k += 3) {
                    j = i.charAt(k + 2);
                    j = 'a' <= j ? j.charCodeAt(0) - 87 : Number(j);
                    j = '+' == i.charAt(k + 1) ? a >>> j : a << j;
                    a = '+' == i.charAt(k) ? a + j & 4294967295 : a ^ j;
                }
            }
            i = '+-3^+b+-f';
            for (var k = 0; k < i.length - 2; k += 3) {
                j = i.charAt(k + 2);
                j = 'a' <= j ? j.charCodeAt(0) - 87 : Number(j);
                j = '+' == i.charAt(k + 1) ? a >>> j : a << j;
                a = '+' == i.charAt(k) ? a + j & 4294967295 : a ^ j;
            }
            a ^= Number(e[1]) || 0;
            0 > a && (a = (a & 2147483647) + 2147483648);
            a %= 1E6;
            return a.toString() + '.' + (a ^ h);
        }
    });
</script>